using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Windows.Forms;
using System.Reflection;
using System.Configuration.Install;

namespace MSNServerService {
	public class Service1 : System.ServiceProcess.ServiceBase {
		/// <summary> 
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Service1() {
			// This call is required by the Windows.Forms Component Designer.
			InitializeComponent();

			// TODO: Add any initialization after the InitComponent call
		}

		// The main entry point for the process
        static void Main()
        {
            System.Diagnostics.Trace.Listeners.Add(new TextWriterTraceListener(System.IO.Path.Combine(MSNConnector.Connection.ServiceResourceFolder, "log.txt")));
            System.AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            bool _IsInstalled = false;
            bool serviceStarting = false; // Thanks to SMESSER's implementation V2.0
            string SERVICE_NAME = "MSNServerService";

            ServiceController[] services = ServiceController.GetServices();

            foreach (ServiceController service in services)
            {
                if (service.ServiceName.Equals(SERVICE_NAME))
                {
                    _IsInstalled = true;
                    if (service.Status == ServiceControllerStatus.StartPending)
                    {
                        // If the status is StartPending then the service was started via the SCM             
                        serviceStarting = true;
                    }
                    break;
                }
            }

            if (!serviceStarting)
            {
                if (_IsInstalled == true)
                {
                    // Thanks to PIEBALDconsult's Concern V2.0
                    DialogResult dr = new DialogResult();
                    dr = MessageBox.Show("Do you REALLY like to uninstall the " + SERVICE_NAME + "?", "Danger", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (dr == DialogResult.Yes)
                    {
                        SelfInstaller.UninstallMe();
                        MessageBox.Show("Successfully uninstalled the " + SERVICE_NAME, "Status",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                else
                {
                    DialogResult dr = new DialogResult();
                    dr = MessageBox.Show("Do you REALLY like to install the " + SERVICE_NAME + "?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (dr == DialogResult.Yes)
                    {
                        SelfInstaller.InstallMe();
                        MessageBox.Show("Successfully installed the " + SERVICE_NAME, "Status",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            else
            {
                // Started from the SCM
                System.ServiceProcess.ServiceBase[] servicestorun;
                servicestorun = new System.ServiceProcess.ServiceBase[] { new Service1() };
                ServiceBase.Run(servicestorun);
            }
        }
        
    

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Trace.WriteLine(e.ExceptionObject.ToString());
            Trace.Flush();
        }

		/// <summary> 
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent() {
			components = new System.ComponentModel.Container();
			this.ServiceName = "MSNServerService";
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing ) {
			if( disposing ) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
		MSNConnector.Connection conn = new MSNConnector.Connection();

		public void Log(string msg) {
			System.IO.Directory.CreateDirectory(@"c:\logs\msn\");
			System.IO.StreamWriter fs = new System.IO.StreamWriter(String.Format(@"c:\logs\msn\log{0}{1}{2}{3}.txt", System.DateTime.Now.Year, System.DateTime.Now.Month, System.DateTime.Now.Day, System.DateTime.Now.Hour),true);
			fs.Write(msg+"\r\n");
			fs.Close();
		}
		System.Timers.Timer t = new System.Timers.Timer(360000);
		/// <summary>
		/// Set things in motion so your service can do its work.
		/// </summary>	
		protected override void OnStart(string[] args) {
            Trace.WriteLine("------------------STARTING SERVICE " + System.DateTime.Now.ToString() + "------------------");

			//NickChangeSpeed
            //string NickChangeSpeed = System.Configuration.ConfigurationSettings.AppSettings["NickChangeSpeed"];
			
            //if(NickChangeSpeed==null||NickChangeSpeed.Trim()=="") NickChangeSpeed = "360000";
            //t.Interval=Convert.ToInt64(NickChangeSpeed);

            //RandomNicksFile = FilePath + "\\RandomNicks.txt";
            //Log("RandomNicksFile="+RandomNicksFile);
            //LoadNicks();
			t.AutoReset=true;
			t.Elapsed+=new System.Timers.ElapsedEventHandler(t_Elapsed);
			t.Enabled=true;
			System.Collections.Specialized.NameValueCollection settings = System.Configuration.ConfigurationSettings.AppSettings;
			string timeout = settings["ConnectionRetryTimeout"];
			if(timeout!=null && timeout.Trim()!="") conn.ConnectionRetryTimeout = Convert.ToInt64( timeout );

			conn.OnLogin+=new MSNConnector.Connection.LoginEventHandler(conn_OnLogin);

			conn.StartMSN(settings["MSNEmail"], settings["MSNPassword"]);

			//t.Start();
						
		}
		public bool LoggedIn = false;

		private void conn_OnLogin(object sender, EventArgs e) {
            //LoggedIn=true;
            //System.Random rnd = new Random();
            //string ScreenNames=System.Configuration.ConfigurationSettings.AppSettings["ScreenNames"];
            //string sn="Anika";			
            //if(ScreenNames!=null && ScreenNames.Trim()!="") {
            //    string[] names = ScreenNames.Split(',');
            //    sn = names[rnd.Next(names.Length-1)];			
            //}
			
            //conn.SetScreenName(sn);
			//System.Threading.Thread.Sleep(60000);
			//conn.SetDisplayPicture(@"c:\metal.jpg");
		}
		/// <summary>
		/// Stop this service.
		/// </summary>
		protected override void OnStop() {
			// TODO: Add code here to perform any tear-down necessary to stop your service.
            Trace.WriteLine("------------------ENDING SERVICE "+System.DateTime.Now.ToString()+"------------------");
            Trace.Flush();
		}
		string FilePath = AppDomain.CurrentDomain.BaseDirectory;
		string RandomNicksFile="";
		System.Collections.ArrayList NickList = new ArrayList();

		private void LoadNicks() {
			System.IO.StreamReader sr = new System.IO.StreamReader(RandomNicksFile);
			string nicks = sr.ReadToEnd();
			sr.Close();
			string[] nicklist = System.Text.RegularExpressions.Regex.Split(nicks,"\r\n");
			foreach(string nick in nicklist) {
				if(nick!=null&&nick.Trim()!="") NickList.Add(nick);
			}
		}

		System.Random rnd = new Random();
		private void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
			//first save the new nick into the list
			//then save the list to disk
			//then grab a random nick and set the screen name
			t.Stop();			
			Log("t_Elapsed");

            //System.Text.StringBuilder sb = new System.Text.StringBuilder();
            //string currentName =conn.GetPartialScreenName();
            //if(!NickList.Contains(currentName)) NickList.Add(currentName);
            //foreach(string nick in NickList) {
            //    if(nick!=null&&nick.Trim()!="") {
            //        sb.Append(nick);
            //        sb.Append("\r\n");
            //    }
            //}
            //System.IO.StreamWriter sw = new System.IO.StreamWriter(RandomNicksFile);
            //sw.Write(sb.ToString());
            //sw.Close();
            //int rndnum = rnd.Next(0,NickList.Count);
            //string newNick = (string)NickList[rndnum];
            //conn.SetScreenName(newNick);
            //Log("NewNick="+newNick);

			t.Start();
		}
	}


    public static class SelfInstaller
    {
        private static readonly string _exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
        public static bool InstallMe()
        {
            try
            {
                ManagedInstallerClass.InstallHelper(
                    new string[] { _exePath });
            }
            catch
            {
                return false;
            }
            return true;
        }

        public static bool UninstallMe()
        {
            try
            {
                ManagedInstallerClass.InstallHelper(
                    new string[] { "/u", _exePath });
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}
